<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2024/1/17} {15:56} 
 */

namespace app\api\logic;


use app\common\model\TabConf;
use think\Db;
use wanghua\general_utility_tools_php\tool\Tools;
use wanghua\general_utility_tools_php\wechat\WechatMsgPush;

/**
 * 参考实战代码案例
 *
 * 所有的消息推送都会进入这个通用逻辑
 *
 * Class WechatMsgPushLogic
 * @package app\api\logic
 */
class WechatMsgPushLogic
{
    protected $token = 'qwer';

    /**
     * desc：运行业务逻辑
     *
     * 微信消息推送入口调用
     *
     * 步骤：
     * 1、先接入微信消息推送
     * 2、调用礼包发放逻辑
     *
     * eg：
     * 调用礼包发放逻辑
     *  function msg(){
            Tools::log_to_write_txt(['微信推送消息.'=>input()]);
            //此行代码包含了消息推送接入逻辑
            return (new \app\api\logic\WechatMsgPushLogic())->run();
        }
     *
     * author：wh
     */
    function run(){
        try {
            $MsgType = input('MsgType');
            $Event = input('Event');
            //微信小游戏的游戏礼包接入逻辑
            if($MsgType == 'event' && $Event == 'minigame_deliver_goods'){
                Tools::log_to_write_txt(['发放微信小游戏礼包,开始：'=>['$MsgType'=>$MsgType,'$Event'=>$Event]]);
                $all_post = input();
                //订单
                if(empty($all_post['MiniGame'])){
                    return json(['ErrCode'=>500,'ErrMsg'=>'礼包不能为空，礼包发放失败']);
                }
                $res = $this->sendMiniGameGiftOrder($all_post['MiniGame']);
                //日志
                Tools::log_to_write_txt(['发放微信小游戏礼包,结束。'=>$res]);
                if($res['code'] == 200){
                    return json(['ErrCode'=>0,"ErrMsg"=>"Success"]);//推荐
                }
                return json(['ErrCode'=>500,'ErrMsg'=>'礼包发放失败']);
            }
            //下方写其它业务逻辑，例如客服等等
            //......

            //消息推送接入逻辑
            return (new WechatMsgPush($this->token))->checkSignature();
        }catch (\Exception $e){
            Tools::error_txt_log($e);
            return 'error';
        }
    }

    /**
     * desc：发放微信小游戏礼包
     *
     * author：wh
     */
    protected function sendMiniGameGiftOrder($MiniGame){

        Tools::log_to_write_txt(['$MiniGame'=>$MiniGame]);
        $MiniGame = is_array($MiniGame)?$MiniGame:json_decode($MiniGame,true);
        $OrderId = $MiniGame['OrderId'];
        $IsPreview = $MiniGame['IsPreview'];
        $SendTime = $MiniGame['SendTime'];
        $ToUserOpenid = $MiniGame['ToUserOpenid'];
        $Zone = $MiniGame['Zone'];

        //$GiftId = $MiniGame['GiftId'];
        //$GiftTypeId = $MiniGame['GiftTypeId'];
        //查询重复
        $order = Db::table(TabConf::$fa_giftorder)->where('orderid',$OrderId)->find();
        if($order){
            return Tools::set_fail('重复礼包');
        }
        Db::startTrans();
        try {
            //新增礼包
            Db::table(TabConf::$fa_giftorder)
                ->data([
                    'orderid'=>$OrderId,
                    'to_user_openid'=>$ToUserOpenid,
                    'is_preview'=>$IsPreview,
                    'zone'=>$Zone,
                    //'gift_typeid'=>$GiftTypeId,
                    //'giftid'=>$GiftId,
                    'send_time'=>date('Y-m-d H:i:s',$SendTime),
                ])
                ->insert();
            $GoodsList = $MiniGame['GoodsList'];
            if(empty($GoodsList)){
                return Tools::set_fail('礼包商品不能为空');
            }
            foreach ($GoodsList as $item){
                //新增礼包商品
                Db::table(TabConf::$fa_giftordergoods)
                    ->data([
                        'orderid'=>$OrderId,//所属订单
                        'prize_id'=>$item['Id'],//奖品id
                        'num'=>$item['Num'],//数量
                    ])
                    ->insert();
                //查询奖品
                $prize = Db::table(TabConf::$fa_prize)
                    ->where('id',$item['Id'])
                    ->find();
                if(empty($prize)){
                    Tools::log_to_write_txt([
                        '奖品不存在，礼包发放失败'
                    ]);
                    continue;//不发
                }
                $users = Db::table(TabConf::$fa_users)
                    ->where('openid',$ToUserOpenid)
                    ->find();
                if(empty($users)){
                    Tools::log_to_write_txt([
                        '用户不存在，礼包发放失败'
                    ]);
                    continue;
                }
                //礼包入账
                Db::table(TabConf::$fa_users)
                    ->where('openid',$ToUserOpenid)
                    ->setInc('score',$prize['val'] * $item['Num']);
            }

            Db::commit();
            return Tools::set_ok();
        }catch (\Exception $e){
            Db::rollback();
            Tools::error_txt_log($e);
            return Tools::set_fail();
        }
    }
}